from mcp.server.fastmcp import FastMCP
from pydantic import AnyHttpUrl
from mcp.server.auth.settings import AuthSettings
from mcp.server.auth.provider import AccessToken, TokenVerifier
import json


class SimpleTokenVerifier(TokenVerifier):
    async def verify_token(self, token: str) -> AccessToken | None:
        print("token", token)
        # 1.验证JWT的签名 2. 验证信息过期时间 3验证信息受众 audience 4.验证令牌授权范围scope
        # _token_001
        if token.startswith("_token_"):
            user_id = token.replace("_token_", "")
            return AccessToken(
                token=token,  # 原始令牌
                sub=user_id,  # 用户标识
                aud="mcp_user",  # 受众
                scope="user",  #  权限
                exp=999999999999,  # 过期时间
                client_id="client_id",  ## 客户端ID
                scopes=["user"],  # 权限范围列表
            )
        return None


mcp = FastMCP(
    name="Resource Server",
    # 配置令牌验证器
    token_verifier=SimpleTokenVerifier(),
    # 配置认证设置
    auth=AuthSettings(
        issuer_url=AnyHttpUrl("https://auth.example.com"),
        resource_server_url=AnyHttpUrl("" "http://127.0.0.1:8000"),
        required_scopes=["user"],  # 要求的权限的范围
    ),
)


@mcp.resource("user://profile")
def get_user_profile() -> str:
    """获取用户资料，这是一个受保护的资源"""
    # FASTMCP会自动进行认证检查，无需手动校验令牌
    # 如果信息无效或选择，FASTMCP会自动拒绝访问
    return json.dumps({"name": "user", "email": "user@qq.com", "role": "user"})


@mcp.tool()
def get_user_data(user_id: str = "current") -> dict[str, str]:
    """获取用户数据(受保护的工作)"""
    if user_id == "current":
        return {
            "user_id": "user_001",
            "status": "active",
            "last_login": "2025年8月31日16:43:59",
        }
    else:
        return {"user_id": user_id, "status": "unknown", "error": "User not found"}


if __name__ == "__main__":
    # 启动HTTP，监听本机的8000端口
    mcp.run(transport="streamable-http")
